package com.ch.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ch.web.admin.entity.XyAdminEntity;
import com.ch.web.admin.mapper.XyAdminDao;
import com.ch.web.admin.request.AdminLoginRequestDto;
import com.ch.web.admin.service.XyAdminService;
import com.ch.web.redis.UserMapCache;
import com.ch.web.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("xyAdminService")
public class XyAdminServiceImpl extends ServiceImpl<XyAdminDao, XyAdminEntity> implements XyAdminService {
    @Value("${token.expire}")
    private Long expire;

    @Autowired
    UserMapCache userMapCache;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<XyAdminEntity> page = this.page(
                new Query<XyAdminEntity>().getPage(params),
                new QueryWrapper<XyAdminEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public R adminLogin(AdminLoginRequestDto adminLoginRequestDto) throws Exception {
        QueryWrapper<XyAdminEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("account", adminLoginRequestDto.getAccount());
        wrapper.eq("password", adminLoginRequestDto.getPassword());
        XyAdminEntity xyAdminEntity = this.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(xyAdminEntity)) {
            String token = TokenGenerator.generateValue();
            Date date = new Date();
            Date expireTime = new Date(date.getTime() + expire);
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("token", token);
            objectObjectHashMap.put("expireTime", expireTime);
            userMapCache.setUserToken(token,xyAdminEntity,expireTime);
            return R.ok(objectObjectHashMap);
        }
        return R.error("账号密码错误");
    }

}
